#!/usr/bin/env python3

import pathlib
from quant.data import ricequant, juejin, jisilu, utils
from quant import strategy
from quant.vlogger import VLogger
from absl import app, flags
import logging
from typing import Dict
from datetime import datetime

FLAGS = flags.FLAGS

flags.DEFINE_string('cache_dir', '/data/quant/conbond', 'Cache directory')
flags.DEFINE_string('start_date', None, 'Data start date')
flags.DEFINE_string('end_date', None, 'Data end date')
flags.DEFINE_enum('freq', '1d', ['1d', '1m'], 'k bar frequency')
flags.DEFINE_enum('source', None,
                  ['ricequant', 'joinquant', 'juejin', 'jisilu', 'combine'],
                  'Data source to refresh')
flags.mark_flag_as_required('source')
flags.DEFINE_string('params_vars', None, 'Conbond strategy parameters')
flags.DEFINE_string('strategy', None, 'Strategy name')


def main(_):
    if FLAGS.source == 'ricequant':
        cache_dir = pathlib.Path(FLAGS.cache_dir).joinpath(
            FLAGS.source, FLAGS.end_date).expanduser()
        ricequant.refresh_conbond(FLAGS.start_date, FLAGS.end_date, FLAGS.freq,
                                  cache_dir)
    elif FLAGS.source == 'joinquant':
        # joinquant.refresh_conbond(FLAGS.start_date, FLAGA.end_date, FLAGS.freq, cache_dir)
        raise Exception('Not updated')
    elif FLAGS.source == 'juejin':
        if FLAGS.end_date is None:
            cache_dir = pathlib.Path(FLAGS.cache_dir).joinpath(
                FLAGS.source, 'latest').expanduser()
            end_date = str(datetime.now().date())
        else:
            cache_dir = pathlib.Path(FLAGS.cache_dir).joinpath(
                FLAGS.source, FLAGS.end_date).expanduser()
            end_date = FLAGS.end_date
        juejin.refresh_conbond(FLAGS.start_date, end_date, FLAGS.freq,
                               cache_dir)
    elif FLAGS.source == 'jisilu':
        cache_dir = pathlib.Path(FLAGS.cache_dir).joinpath(
            FLAGS.source).expanduser()
        logging.getLogger().setLevel(logging.INFO)
        _, df = jisilu.refresh_now(cache_dir, FLAGS.end_date)
        if FLAGS.strategy is not None:
            pvars: Dict = eval(FLAGS.params_vars)
            cfg = strategy.ConbondStrategy.strategy_cfg(FLAGS.strategy, pvars)
            st = strategy.ConbondRotateStrategy(cfg,
                                                lambda context, bar_dict: df)
            VLogger.v = 2
            st.generate_signal(df, datetime.now())
    elif FLAGS.source == 'combine':
        juejin_dir = pathlib.Path(FLAGS.cache_dir).joinpath(
            'juejin', 'latest').expanduser()
        jsl_dir = pathlib.Path(FLAGS.cache_dir).joinpath('jisilu').expanduser()
        ins, bars = utils.combine_juejin_jsl(juejin_dir, jsl_dir,
                                             FLAGS.start_date, FLAGS.freq)
        ins.to_csv(juejin_dir.joinpath('all_instruments_combined.csv'))
        bars.to_csv(
            juejin_dir.joinpath('conbonds_%s_combined.csv' % FLAGS.freq))


if __name__ == '__main__':
    app.run(main)
